import axios from "axios"; // 引入axios
import DonMessage from "../common/js/message";
import router from "@/router";
let { NODE_ENV } = process.env;
import { ssoDomain, appId } from "@/utils/config";

//连接mock连接
const http = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API,
  timeout: 100000,
  responseType: "json",
  withCredentials: true,
  headers: {
    httponly: true,
    secure: true,
    // loginUser:"test"
  },
});
/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url, params, config = {}) {
  return new Promise((resolve, reject) => {
    http
      .get(url, { params: params, ...config })
      .then((res) => {
        if (config.responseType) {
          resolve(res);
        } else {
          resolve(res.data);
        }
      })
      .catch((err) => {
        console.log(err);
        let loadingDom = document.querySelector(".el-loading-mask.loading");
        loadingDom && loadingDom.remove();
        reject(err.data);
      });
  });
}
/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 * @param {object} config [请求时携带的参数]
 */
export function post(url, params) {
  return new Promise((resolve, reject) => {
    http
      .post(url, params)
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        console.log(err);
        let loadingDom = document.querySelector(".el-loading-mask.loading");
        loadingDom && loadingDom.remove();
        reject(err.data);
      });
  });
}
/**
 * @函数功能:请求拦截器 添加请求头
 * @参数输入:
 * @函数返回:
 */
http.interceptors.request.use(
  (config) => {
    if (NODE_ENV === "development" || NODE_ENV === "prodTest") {
      config.headers["loginUser"] = "test";
    }
    return config;
  },
  (err) => {
    console.log(err);
    return Promise.reject(err);
  },
);

/**
 * @函数功能:拦截器
 * @参数输入:
 * @函数返回:
 */
http.interceptors.response.use(
  (data) => {
    //不做这个判断 如果后台格式不对，这里面代码出错，就会报 Uncaught (in promise) undefined错误
    if (!data.data) {
      return data;
    }
    if (data.data.code === "403") {
      router.push({ path: "/403" });
      return Promise.reject(err);
    }
    if (data.data.code === "302") {
      let now_url = encodeURIComponent(window.location.href);
      let url = `${ssoDomain[NODE_ENV]}/auth/sso/login?app_id=${appId[NODE_ENV]}&jumpto=${now_url}`;
      location.href = url;
      return Promise.reject(err);
    }
    if (data.data.code != 0) {
      new DonMessage().warning({
        message: data.data.msg,
      });
      return Promise.reject(err);
    }
    return data;
  },
  (err) => {
    new DonMessage().error({
      message: `程序出错了，请联系管理员：${err.response.statusText}（${err.response.status}）`,
    });
    return Promise.reject(error);
  },
);
